package com.lw.leetcode.str.b;

import java.util.HashSet;
import java.util.Set;

/**
 * Created with IntelliJ IDEA.
 * 963. 最小面积矩形 II
 *
 * @author liw
 * @version 1.0
 * @date 2022/3/13 20:33
 */
public class MinAreaFreeRect {

    public double minAreaFreeRect(int[][] points) {
        int length = points.length;
        if (length < 4) {
            return 0;
        }

        Set<Integer> set = new HashSet<>();
        for (int i = 0; i < length; i++) {
            set.add(points[i][0] * 40000 + points[i][1]);
        }

        double area = Double.MAX_VALUE;
        for (int i = 0; i < length; i++) {
            for (int j = i + 1; j < length; j++) {
                int d2ij = distance2(points[i], points[j]);
                for (int k = j + 1; k < length; k++) {
                    int d2ik = distance2(points[i], points[k]);
                    int d2jk = distance2(points[j], points[k]);
                    if (d2ij + d2ik != d2jk) {
                        continue;
                    }

                    int x = points[j][0] + points[k][0] - points[i][0];
                    int y = points[j][1] + points[k][1] - points[i][1];
                    if (!set.contains(x * 40000 + y)) {
                        continue;
                    }
                    area = Math.min(area, Math.sqrt(d2ij) * Math.sqrt(d2ik));
                }
            }
        }
        return area == Double.MAX_VALUE ? 0D : area;
    }

    private int distance2(int[] a, int[] b) {
        return (b[0] - a[0]) * (b[0] - a[0]) + (b[1] - a[1]) * (b[1] - a[1]);
    }

}
